﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using CleverDD.Helper;
using CleverDD.Helper.Tool;
using CleverDD.Model.Communication.PLC;
using CleverDD.Model.Param;
using FrameWorkDemo.UC;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace FrameWorkDemo.Communication.PLC
{
    public partial class EditPlcForm : Form
    {
        public EditPlcForm()
        {
            InitializeComponent();
            InitControl();
        }


        #region 变量定义

        private List<PlcInfoEntity> _plcInfoList = new List<PlcInfoEntity>();
        private int _comIndex;
        private string _currentGuid;
        #endregion

        #region 初始化
        public void InitControl()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            this.StartPosition = FormStartPosition.CenterParent;




            ListView.FullRowSelect = true;
            ListView.View = View.Details;  // 设置视图为 Details 模式以显示列标题
            ListView.Dock = DockStyle.Fill;

            // 添加四列标题
            ListView.Columns.Add("ID", 0);
            ListView.Columns.Add("序号", 50);
            ListView.Columns.Add("名称", 100);
            ListView.Columns.Add("状态", 60);

            ListView.SelectedIndexChanged += new System.EventHandler(this.ListView_SelectedIndexChanged);
        }


        private void EditPlcForm_Load(object sender, EventArgs e)
        {
            LoadPlcInfoList();

            List<ParamInfo> paramList = new List<ParamInfo>
            {
                new ParamInfo("序号"),
                new ParamInfo("名称"),
                new ParamInfo("IP" ),
                new ParamInfo("端口号")
            };
            ParamInfo typeParam = new ParamInfo
            {
                LabelName = "PLC类型",
                ParamType = ParamType.ComboBox,
                ValueList = new List<string>(Enum.GetNames(typeof(PlcType))),
            };
            paramList.Add(typeParam);

            ParamInfo inUseParam = new ParamInfo
            {
                LabelName = "是否启用",
                ParamType = ParamType.YesOrNo
            };
            paramList.Add(inUseParam);
            BasicParamUc.InitControl(paramList);


            if (ListView.Items.Count > 0)
            {
                ListView.Items[0].Selected = true;
                ListView.EnsureVisible(0); // 确保第一行可见
                ListView.Focus();          // 设置焦点以便显示选择状态
            }
        }

        #endregion

        #region 控件方法

        private void ListView_SelectedIndexChanged(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            if (ListView.SelectedItems.Count == 0)
            {
                _currentGuid = "";
                for (int i = 0; i < 6; i++)
                {
                    list.Add("");
                }
                BasicParamUc.InitData(list);
                return;
            }
            _comIndex = ListView.SelectedIndices[0];
            _currentGuid = this.ListView.Items[_comIndex].SubItems[0].Text.Trim();

            //根据guid找到选中的对象
            PlcInfoEntity selectedItem = _plcInfoList.FirstOrDefault(p => p.Guid == Guid.Parse(_currentGuid));
            //将选中对象的属性转成字符串的形式，传给详情界面 
            if (selectedItem != null)
            {
                list.Add(selectedItem.SortIndex + "");
                list.Add(selectedItem.Name + "");
                list.Add(selectedItem.Ip + "");
                list.Add(selectedItem.Port + "");
                list.Add(selectedItem.PlcType + "");
                list.Add(selectedItem.IsInUse + "");
            }

            BasicParamUc.InitData(list);

        }


        private void NewBtn_Click(object sender, EventArgs e)
        {

            BasicParamUc.GetAllValue();
            PlcInfoEntity plcInfo = new PlcInfoEntity();
            plcInfo.Guid = Guid.NewGuid();


            int.TryParse(BasicParamUc.ParamList[0].NewValue, out int sortIndex);
            plcInfo.SortIndex = _plcInfoList.Any()
                ? Math.Max(sortIndex, _plcInfoList.Max(t => t.SortIndex)+1)
                : sortIndex;

            plcInfo.Name = BasicParamUc.ParamList[1].NewValue;
            plcInfo.Ip = BasicParamUc.ParamList[2].NewValue;
            int.TryParse(BasicParamUc.ParamList[3].NewValue, out plcInfo.Port);
            Enum.TryParse(BasicParamUc.ParamList[4].NewValue, out plcInfo.PlcType);
            bool.TryParse(BasicParamUc.ParamList[5].NewValue, out plcInfo.IsInUse);

            if ("".Equals(plcInfo.Name))
            {
                MessageBox.Show("名称不能为空");
                return;
            }

            bool sameNameFlag = _plcInfoList.Any(obj => obj.Name == plcInfo.Name);

            if (sameNameFlag)
            {
                MessageBox.Show("名称不能相同");
                return;
            }

            _plcInfoList.Add(plcInfo);
            SavaPlcInfoList();

        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            if ("".Equals(_currentGuid))
            {
                MessageBox.Show("未选中数据");
                return;
            }
            BasicParamUc.GetAllValue();
            foreach (var plcInfo in _plcInfoList)
            {
                if (plcInfo.Guid == Guid.Parse(_currentGuid))
                {
                    int.TryParse(BasicParamUc.ParamList[0].NewValue, out plcInfo.SortIndex);
                    plcInfo.Name = BasicParamUc.ParamList[1].NewValue;
                    plcInfo.Ip = BasicParamUc.ParamList[2].NewValue;
                    int.TryParse(BasicParamUc.ParamList[3].NewValue, out plcInfo.Port);
                    Enum.TryParse(BasicParamUc.ParamList[4].NewValue, out plcInfo.PlcType);
                    bool.TryParse(BasicParamUc.ParamList[5].NewValue, out plcInfo.IsInUse);
                    break;
                }
            }
            SavaPlcInfoList();
        }

        private void DelBtn_Click(object sender, EventArgs e)
        {
            if ("".Equals(_currentGuid))
            {
                MessageBox.Show("未选中数据");
                return;
            }
            _plcInfoList.RemoveAll(p => p.Guid == Guid.Parse(_currentGuid));
            SavaPlcInfoList();
        }

        private void EditAddressBtn_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_currentGuid))
            {
                MessageBox.Show("未选中数据");
                return;
            }


            EditPlcAddressForm form = new EditPlcAddressForm(Guid.Parse(_currentGuid));

            form.ShowDialog();
        }

        #endregion

        #region 主要方法

        public void SavaPlcInfoList()
        {
            StaticTool.SavaPlcInfoList(_plcInfoList);
            LoadPlcInfoList();
        }


        public void LoadPlcInfoList()
        {
            _plcInfoList = StaticTool.LoadPlcInfoList();

            this.ListView.Items.Clear();
            foreach (var item in _plcInfoList)
            {
                ListViewItem lvi = new ListViewItem
                {
                    Text = item.Guid + ""
                };
                lvi.SubItems.Add(item.SortIndex + "");
                lvi.SubItems.Add(item.Name);
                lvi.SubItems.Add(item.IsInUse ? "启用" : "停用");
                this.ListView.Items.Add(lvi);
            }
        }

        #endregion


       
    }
}
